<?php


require_once('Doctrine/Query.php');
require_once('Db/Shop/Record/User.php');
require_once('Zend/Validate/Abstract.php');

class Demo_UsernameValidator extends Zend_Validate_Abstract
{
	/**
	 * Containt for id of error message.
	 *
	 */
    const USER_EXISTS = 'userExists';
    /**
     * Array of error messages.
     *
     * @var array
     */
    protected $_messageTemplates = array(self::USER_EXISTS => "User with this username already exists");	
	
    /**
     * Returns true if and only if $value meets the validation requirements
     *
     * If $value fails validation, then this method returns false, and
     * getMessages() will return an array of messages that explain why the
     * validation failed.
     *
     * @param  mixed $value
     * @return boolean
     * @throws Zend_Valid_Exception If validation of $value is impossible
     */
    public function isValid($value)
    {
        $query = new Doctrine_Query();
        $user = $query->select('username')
              ->from('Db_Shop_Record_User u')
              ->where('u.username = ?', $value)
              ->execute();
        $result = count($user)>0 ? false : true;
        if (!$result) {
            $this->_error(self::USER_EXISTS);
        }
        return $result;
    }
}